package com.example.beikeyigou.goods;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.beikeyigou.R;
import com.example.beikeyigou.custom.HorizontalListView;
import com.example.beikeyigou.dialog.BuyNowDialog;
import com.example.beikeyigou.login_reg.UserBean;
import com.example.beikeyigou.pay.PayActivity;
import com.example.beikeyigou.utils.BaseActivity;
import com.example.beikeyigou.utils.SaveUserUtils;
import com.example.beikeyigou.utils.URLUtils;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GoodsDetailsActivity extends BaseActivity {
    private ImageView backImg, goodImg;
    private TextView priceTv, nameTv, informationTv, countTv;
    private Button buyNowBtn, toTrolleyBtn;
    private HorizontalListView guessLv;

    private int id, flag;
    GoodBean.DataBean goodData;      // 当前页面的数据
    List<GoodsBean.DataBean> likeData;      // 猜你喜欢的数据源
    private GoodsType2Adapter likeAdapter;
    boolean isLogin = false;

    UserBean.DataBean userData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);
        // 接受数据
        id = getIntent().getIntExtra("id", -1);

        findView();
        initData();
        setListener();
        changeStatusBarTextImgColor(true);
    }

    public void changeStatusBarTextImgColor(boolean color) {
        if (color) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        } else {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);//恢复状态栏白色字体
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    private void refreshData() {
        if (goodData == null) {
            Toast.makeText(this,"无数据",Toast.LENGTH_SHORT).show();
            return;
        }
        priceTv.setText("￥"+String.valueOf(goodData.getPrice()));
        nameTv.setText(goodData.getName());
        informationTv.setText(goodData.getInfo());
        String photo = goodData.getPhoto();
        if (!TextUtils.isEmpty(photo)) {
            String photoUrl = URLUtils.PUBLIC_URL+photo;
            Picasso.with(this).load(photoUrl).into(goodImg);
        }
        countTv.setText("库存: "+goodData.getCount());
    }

    private void initData() {
        flag = 0;
        likeData = new ArrayList<>();
        flag = 0;
        getNetwork(URLUtils.queryCommodityInfo_url+id);
        likeAdapter = new GoodsType2Adapter(this, likeData);
        guessLv.setAdapter(likeAdapter);

        if (SaveUserUtils.getUserData(this) != null) {
            isLogin = true;
        }

        userData = SaveUserUtils.getUserData(this);
    }

    @Override
    public void onSuccess(String result) {
        super.onSuccess(result);
        if (flag == 0) {
            GoodBean goodBean = new Gson().fromJson(result, GoodBean.class);
            switch (goodBean.getCode()) {
                case 200:
                    goodData = goodBean.getData();
                    getNetwork(URLUtils.guessYouLike_url);
                    flag = 1;
                    break;
                case 201:
                    Toast.makeText(this, "查询失败", Toast.LENGTH_SHORT).show();
                    break;
                case 400:
                    Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        } else if (flag == 1) {
            GoodsBean goodsBean = new Gson().fromJson(result, GoodsBean.class);
            switch (goodsBean.getCode()) {
                case 200:
                    List<GoodsBean.DataBean> list = goodsBean.getData();
                    likeData.addAll(list);
                    refreshData();
                    likeAdapter.notifyDataSetChanged();
                    flag = 2;
                    break;
                case 201:
                    Toast.makeText(this, "查询失败", Toast.LENGTH_SHORT).show();
                    break;
                case 400:
                    Toast.makeText(this, "参数错误", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        } else {
            GoodsBean goodsBean = new Gson().fromJson(result, GoodsBean.class);
            switch (goodsBean.getCode()) {
                case 200:
                    Toast.makeText(this, "添加成功！在购物车等亲~", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.goods_details_buyNow_btn:
                    if (isLogin) {      // 已登录
                        BuyNowDialog dialog = new BuyNowDialog(GoodsDetailsActivity.this);
                        dialog.show();

                        ImageView imageView = dialog.getGoodImg();
                        String photo = goodData.getPhoto();
                        if (!TextUtils.isEmpty(photo)) {
                            String photoUrl = URLUtils.PUBLIC_URL+photo;
                            Picasso.with(GoodsDetailsActivity.this).load(photoUrl).into(imageView);
                        }

                        dialog.setGoodPrice("￥" + String.valueOf(goodData.getPrice()))
                                .setRemainNum(String.valueOf("库存: " + goodData.getCount()))
                                .setOnEnsureListener(new BuyNowDialog.OnEnsureListener() {
                            @Override
                            public void onEnsure(int num) {
                                Map<String, String> map = new HashMap<>();
                                map.put("count", String.valueOf(num));
                                map.put("commodityId", String.valueOf(goodData.getId()));
                                map.put("totalPrice", String.valueOf(goodData.getPrice() * num));
                                map.put("commodityName", goodData.getName());
                                map.put("photo", goodData.getPhoto());
                                Intent intent = new Intent(GoodsDetailsActivity.this, PayActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("mapData", (Serializable) map);
                                intent.putExtras(bundle);
                                intent.putExtra("flag", 1);
                                startActivity(intent);
                                dialog.dismiss();
                            }
                        });
                    } else {            // 未登录
                        Toast.makeText(GoodsDetailsActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.goods_details_buyLater_btn:
                    if (isLogin) {      // 已登录
                        BuyNowDialog dialog = new BuyNowDialog(GoodsDetailsActivity.this);
                        dialog.show();

                        ImageView imageView = dialog.getGoodImg();
                        String photo = goodData.getPhoto();
                        if (!TextUtils.isEmpty(photo)) {
                            String photoUrl = URLUtils.PUBLIC_URL+photo;
                            Picasso.with(GoodsDetailsActivity.this).load(photoUrl).into(imageView);
                        }

                        dialog.setGoodPrice("￥" + String.valueOf(goodData.getPrice()))
                                .setStorage_num(goodData.getCount())
                                .setRemainNum(String.valueOf("库存: " + goodData.getCount()))
                                .setOnEnsureListener(new BuyNowDialog.OnEnsureListener() {
                                    @Override
                                    public void onEnsure(int num) {
                                        Map<String, String> map = new HashMap<>();
                                        map.put("userId", String.valueOf(userData.getId()));
                                        map.put("commodityId", String.valueOf(goodData.getId()));
                                        map.put("count", String.valueOf(num));
                                        flag = 2;
                                        postNetwork(URLUtils.insertShoppingCar_url, map);
                                        dialog.dismiss();
                                    }
                                });
                    } else {            // 未登录
                        Toast.makeText(GoodsDetailsActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.goods_details_back:
                    finish();
            }
        }
    };

    private void setListener() {
        backImg.setOnClickListener(listener);
        buyNowBtn.setOnClickListener(listener);
        toTrolleyBtn.setOnClickListener(listener);

        guessLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                likeAdapter.setClickPos(position);
                Intent intent = new Intent(GoodsDetailsActivity.this, GoodsDetailsActivity.class);
                intent.putExtra("id", likeData.get(position).getId());
                startActivity(intent);
            }
        });
    }

    private void findView() {
        backImg = findViewById(R.id.goods_details_back);
        goodImg = findViewById(R.id.goods_details_img);
        priceTv = findViewById(R.id.goods_details_price);
        nameTv = findViewById(R.id.goods_details_name);
        informationTv = findViewById(R.id.goods_details_information);
        buyNowBtn = findViewById(R.id.goods_details_buyNow_btn);
        toTrolleyBtn = findViewById(R.id.goods_details_buyLater_btn);
        countTv = findViewById(R.id.goods_details_count);
        guessLv = findViewById(R.id.goods_details_guess_lv);
    }
}